//
//  DeviceSettingView.swift
//  Kosspot
//
//  Created by 李鑫 on 2025/7/14.
//

import SwiftUI
import UTEBluetoothRYApi
import ToastUI
import PhotosUI

struct DeviceSettingView: View {
    @EnvironmentObject var appState: AppState
    @StateObject var viewModel = DeviceDetailVM()
    @State var showToast: Bool = false
    @Binding var item: UTEModelDevice
    @State private var permissionAlertType: PermissionAlertType = .camera
    @State private var sourceType: UIImagePickerController.SourceType = .camera
    @State private var showImagePicker = false
    @State private var showPermissionAlert = false
    @State private var selectedImage: UIImage?
    
    var body: some View {
        VStack {
            CustomNavigationBar(rightImageName:nil, title: item.name) {}
            ScrollView(.vertical) {
                HStack {
                    VStack (alignment: .leading, spacing: 14) {
                        HStack {
                            Text("设备ID：\(item.advertisementAddress)").font(.system(size: 16))
                                .foregroundStyle(.white)
                        }
                        HStack{
                            Circle().fill(Color(hex: "#00F3AF"))
                                .frame(width: 6,height: 6)
                            Text(item.isConnected ? "已连接": "未连接").font(.system(size: 14))
                                .foregroundStyle(Color(hex: "#C6C6C6"))
                            Spacer()
                        }
                        HStack {
                            Text("\(viewModel.batteryPer)%").font(.system(size: 14))
                                .foregroundStyle(Color(.white))
                            Image("dianlaing")
                            Spacer()
                        }
                    }
                    .padding(.top,57)
                    .padding(.leading,40)
                    Spacer()
                    Image("watchIcon")
                        .resizable()
                        .frame(width: 100,height: 166)
                        .padding(.trailing,40)
                    
                    
                }.frame(height: 166)
                
                Spacer().frame(height: 20)
                VStack {
                    HStack {
                        Text("表盘市场").font(.system(size: 16))
                            .foregroundStyle(.white)
                        Spacer()
                        Image("xiangyou")
                            .resizable()
                            .frame(width: 16,height: 16)
                            .onTapGesture {
                                //跳转到表盘
                                
                            }
                    }.padding(.horizontal,20)
                    Spacer().frame(height: 20)
                    ScrollView(.horizontal,showsIndicators: false){
                        HStack(spacing: 38) {
                            WatchIcon(iconImageName: "iconImageName", iconName: "表盘名称")
                            WatchIcon(iconImageName: "iconImageName", iconName: "表盘名称")
                            WatchIcon(iconImageName: "iconImageName", iconName: "表盘名称")
                            WatchIcon(iconImageName: "iconImageName", iconName: "表盘名称")
                        }
                    }
                }
                .frame(height: 172)
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
                
                Spacer().frame(height: 12)
                ItemView(titleImageName:"通知", title: "消息推送") {
                    //消息推送
                    appState.navigateTo(.messagepush)
                }
                .frame(height: 56)
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
                
                Spacer().frame(height: 12)
                
                VStack {
                    ItemView(titleImageName:"电子卡包", title: "电子卡包") {
                        appState.navigateTo(.electroniccard)
                    }.frame(height: 56)
                    ItemView(titleImageName:"日常闹钟", title: "日常闹钟") {
                        //日常闹钟
                        appState.navigateTo(.clocklist)
                    }.frame(height: 56)
                    ItemView(titleImageName:"日历", title: "日历") {
                        //日历
                    }.frame(height: 56)
                    ItemView(titleImageName:"世界时钟", title: "世界时钟") {
                        //世界时钟
                    }.frame(height: 56)
                    
                    ItemView(titleImageName:"拍照控制", title: "拍照控制") {
                        //拍照控制
                        checkCameraPermission()
                    }.frame(height: 56)
                }
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
                .onChange(of: showImagePicker) {
                    newValue in
                    if newValue {
                        showImagePicker = false
                        appState.navigateTo(.takePhote)
                    }
                }
                .alert(isPresented: $showPermissionAlert) {
                    Alert(
                        title: Text("相机权限被拒绝"),
                        message: Text("请在设置中允许访问相机以拍摄照片"),
                        primaryButton: .default(Text("设置")) {
                            openSettings()
                        },
                        secondaryButton: .cancel(Text("取消"))
                    )
                }
                
                Spacer().frame(height: 12)
                VStack {
                    ItemView(titleImageName:"查找手表", title: "查找手表") {
                        //查找手表
                        viewModel.findWearDevice(cmd: 1)
                    }.frame(height: 56)
                    ItemView(titleImageName:"其他设置", title: "其他设置") {
                        //其他设置
                        appState.navigateTo(.otherSetting)
                    }.frame(height: 56)
                    ItemView(titleImageName:"固件升级", title: "固件升级") {
                        //固件升级
                        appState.navigateTo(.firmupdate)
                    }.frame(height: 56)
                }
                .background(Color(hex: "#1E1E1E"))
                .cornerRadius(16)
                .padding(.horizontal,12)
            }
            
            Spacer().frame(height: 20)
            HStack {
                Button {
                    viewModel.unboundType(type: 1)
                } label: {
                    Text("解除绑定")
                        .font(.system(size: 16))
                        .foregroundStyle(Color(hex: "#242424"))
                }
            }
            .frame(maxWidth: .infinity, alignment: .center)
            .frame(height: 44)
            .gradientBackground(colors: [Color(hex: "#00F3AF"),Color(hex: "#00E9DA")], type: .linear(start: .leading, end: .trailing), cornerRadius: 22.0)
            .padding(.horizontal,12)
            .padding(.bottom,20)
            .toast(isPresented: $showToast) {
                ShowMessageView(message: viewModel.errorStr)
            }
            .onChange(of: viewModel.errorStr) {
                newValue in
                if let errorMessage = newValue, !errorMessage.isEmpty {
                    showToast = true
                    DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
                        showToast = false
                        viewModel.errorStr = nil
                       
                    }
                }
            }
            
        }.navigationBarHidden(true)
            .background(Color(hex: "#0A0A0A"))
            .edgesIgnoringSafeArea(.all)
            .onAppear {
                viewModel.getBatteryInfo()
//                viewModel.getDeviceInfo()
//                viewModel.getWatchFaceParams()
//                viewModel.fetchWatchFaces()
//                viewModel.getImageWatchFaceModel()
//                viewModel.getBatteryInfo()
//                viewModel.getDefaultConfiguration()
               
            }
            .onDisappear {
                
            }
    }
    
    private func checkCameraPermission() {
        let status = AVCaptureDevice.authorizationStatus(for: .video)
        permissionAlertType = .camera
        switch status {
        case .authorized:
            sourceType = .camera
            showImagePicker = true
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                DispatchQueue.main.async {
                    if granted {
                        sourceType = .camera
                        showImagePicker = true
                    } else {
                        showPermissionAlert = true
                    }
                }
            }
        default:
            showPermissionAlert = true
        }
    }
    
    private func openSettings() {
        if let url = URL(string: UIApplication.openSettingsURLString) {
            UIApplication.shared.open(url)
        }
    }
    
    
    
}




struct WatchIcon: View {
    @State var iconImageName:String
    @State var iconName:String
    var body: some View {
        VStack {
            Image(iconImageName)
                .resizable()
                .frame(width: 70,height: 70)
            Spacer().frame(height: 12)
            Text(iconName)
                .font(.system(size: 14))
                .foregroundStyle(.white)
        }
    }
}


struct ItemView: View {
    @State var titleImageName:String
    @State var title:String
    var onTap: () -> Void
    var body: some View {
        HStack {
            Image(titleImageName)
                .resizable()
                .frame(width: 32,height: 32)
                .padding(.leading,20)
            
            Text(title)
                .font(.system(size: 16))
                .foregroundStyle(.white)
            Spacer()
            Image("xiangyou")
                .resizable()
                .frame(width: 16,height: 16)
                .padding(.trailing,20)
        }
        .onTapGesture {
            onTap()
        }
    }
}
